package org.redmagic.location.web;

import java.util.List;

import org.redmagic.api.HttpConnection;
import org.redmagic.api.Location;
import org.redmagic.utils.Hierarchies;

public class WebLocation implements Location {

    private final String uri;
    private final List<String> hierarchy;
    private final HttpConnection connection;
    
    public WebLocation(String uri, List<List<String>> attempts) {
        this(uri, attempts, new SimpleHttpConnection());
    }
    
    public WebLocation(String uri, List<List<String>> attempts, HttpConnection connection) {
        this.uri = (uri.endsWith("/") ? uri : uri + "/");
        this.hierarchy = Hierarchies.toHierarchies(attempts);
        this.connection = connection;
    }
    
    public String resolve(String placeholder) {
        String result = null;
        for (String tags : hierarchy) {
            result = callWebService(placeholder, tags);
            if (result != null) {
                break;
            }
        }
        return result;
    }

    private String callWebService(String placeholder, String tags) {
        String url = buildUrl(placeholder, tags);
        return connection.call(url);
    }

    String buildUrl(String placeholder, String suffix) {
        String url = uri + placeholder;
        if (!suffix.isEmpty()) {
            url = url + "?" + suffix;
        }
        return url;
    }
}